package general

import (
	"os"
	"time"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
)

// parseKubeconfig 解析 Kubeconfig
func parseKubeconfig(data string) (*api.Config, error) {
	// 创建临时文件并写入 Kubeconfig 内容
	tmpFile, err := os.CreateTemp("", "kubeconfig")
	if err != nil {
		return nil, err
	}
	defer os.Remove(tmpFile.Name()) // 用完后删除临时文件

	if _, err := tmpFile.Write([]byte(data)); err != nil {
		return nil, err
	}

	if err := tmpFile.Close(); err != nil {
		return nil, err
	}

	return clientcmd.LoadFromFile(tmpFile.Name())
}

// GetClientset 根据 Kubeconfig 数据获取 Kubernetes clientset
func GetClientset(kubeconfigData string) (*kubernetes.Clientset, error) {
	kubeconfig, err := parseKubeconfig(kubeconfigData)
	if err != nil {
		return nil, err
	}

	clientConfig, err := clientcmd.NewNonInteractiveClientConfig(*kubeconfig, "", &clientcmd.ConfigOverrides{}, nil).ClientConfig()
	if err != nil {
		return nil, err
	}

	return kubernetes.NewForConfig(clientConfig)
}

// TaskInfo 描述单个任务的信息
type TaskInfo struct {
	TaskID         string
	ControllerName string
	Namespace      string
	ControllerType string
}

// AlarmEventResult 表示单个任务的通用报警事件结果
type AlarmEventResult struct {
	Result       string    `json:"alarm_event_result"`
	ResultTime   time.Time `json:"alarm_event_result_time"`
	ResultStatus string    `json:"alarm_event_result_status"`
	Error        error     `json:"-"`
}
